package com.dhcc.core.modules.system.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.OnlineSession;
import com.dhcc.core.modules.system.entity.OnlineSession.OnlineStatus;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.core.modules.system.entity.UserOnline;
import com.dhcc.core.modules.system.service.ISessionService;

@Service("sessionService")
public class SessionServiceImpl implements ISessionService {

	@Autowired
	private SessionDAO sessionDAO;

	@Override
	public List<UserOnline> list(String searchKey) {
		List<UserOnline> list = new ArrayList<>();
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for (Session s : sessions) {
		    OnlineSession session = (OnlineSession) s;
			UserOnline userOnline = new UserOnline();
			SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
			if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
				continue;
			} else {
				principalCollection = (SimplePrincipalCollection) session
						.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
				User user = (User) principalCollection.getPrimaryPrincipal();
				userOnline.setName(user.getName());
				userOnline.setLoginName(user.getLoginName());
				userOnline.setDeptName(user.getDeptName());
				userOnline.setPositionName(user.getPositionName());
			}
			userOnline.setId((String) session.getId());
			userOnline.setIpaddr(session.getHost());
			userOnline.setStartTimestamp(session.getStartTimestamp());
			userOnline.setLastAccessTime(session.getLastAccessTime());
			Long timeout = session.getTimeout();
			if (timeout == 0l) {
				userOnline.setStatus(OnlineStatus.off_line);
			}
			userOnline.setTimeout(timeout);
			userOnline.setBrowser(session.getBrowser());
			userOnline.setOs(session.getOs());
			if(CommonUtil.isNotEmpty(searchKey)){
                if(userOnline.getName().indexOf(searchKey)>-1){
                    list.add(userOnline);
                }else if(userOnline.getLoginName().indexOf(searchKey)>-1){
                    list.add(userOnline);
                }
			}else{
	            list.add(userOnline);
			}
		}
		return list;
	}

	@Override
	public boolean forceLogout(String sessionId) {
		Session session = sessionDAO.readSession(sessionId);
		session.setTimeout(0);
		return true;
	}

}
